<script setup>
import { RouterView } from "vue-router";
import { Layout, Menu, Avatar, Dropdown, Switch, message } from "ant-design-vue";
import { useRouter, useRoute } from "vue-router";
import {
  HomeOutlined,
  FileTextOutlined,
  AppstoreOutlined,
  TagOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LogoutOutlined,
  SettingOutlined,
  BulbOutlined,
  EyeInvisibleOutlined,
  PictureOutlined,
} from "@ant-design/icons-vue";
import { ref, computed, onMounted } from "vue";

// 导入认证相关API和工具
import authApi from "@/api/auth";
import { settingApi } from "@/api/setting";
import { checkLoginStatus } from "./utils/authUtils";
import { eventBus } from "./utils/eventBus";

const router = useRouter();
const route = useRoute();
const { Header, Content, Sider } = Layout;
const collapsed = ref(false);
const currentUser = ref({
  name: "管理员",
  avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=admin",
});

// 获取个人信息
const fetchPersonalInfo = async () => {
  try {
    const response = await settingApi.getPersonalInfo();
    if (response.code === 200 && response.data && response.data.data) {
      const data = response.data.data;
      currentUser.value.name = data.name || "管理员";
      // 处理头像URL，添加基础路径
      if (data.avatar) {
        currentUser.value.avatar =
          import.meta.env.VITE_API_BASE_URL + data.avatar;
      }
    }
  } catch (error) {
    console.error("获取个人信息失败:", error);
  }
};

// 菜单项配置
const menuItems = [
  {
    key: "dashboard",
    icon: HomeOutlined,
    label: "仪表盘",
    path: "/dashboard",
  },
  {
    key: "articles",
    icon: FileTextOutlined,
    label: "文章管理",
    path: "/articles",
  },
  {
    key: "categories",
    icon: AppstoreOutlined,
    label: "分类管理",
    path: "/categories",
  },
  {
    key: "tags",
    icon: TagOutlined,
    label: "标签管理",
    path: "/tags",
  },
  {
    key: "imageBed",
    icon: PictureOutlined,
    label: "图床管理",
    path: "/image-bed",
  },
  {
    key: "systemSettings",
    icon: SettingOutlined,
    label: "系统设置",
    path: "/system/settings",
  },
  {
    key: "personalInfo",
    icon: UserOutlined,
    label: "个人信息",
    path: "/personal-info",
  },
];

// 处理退出登录
const handleLogout = async () => {
  try {
    // 使用authApi中的logout方法移除token
    await authApi.logout();
    
    // 清除本地状态
    isLoggedIn.value = false;
    currentUser.value = { name: '', avatar: '' };
    
    // 重定向到登录页面
    await router.push({ name: "login" });
    
    // 显示退出成功消息
    message.success('退出登录成功');
  } catch (error) {
    console.error('退出登录失败:', error);
    
    // 即使API调用失败，也要清除本地token和状态
    localStorage.removeItem('adminToken');
    isLoggedIn.value = false;
    currentUser.value = { name: '', avatar: '' };
    
    // 强制跳转到登录页面
    await router.push({ name: "login" });
    
    message.warning('退出登录完成');
  }
};

// 已移除: 不再需要手动管理下拉菜单状态和userMenuItems数组，
// 使用官网推荐的<a-menu>和<template #overlay>方式实现下拉菜单

// 获取当前激活的菜单项
const currentMenuKey = computed(() => {
  const path = route.path;
  const item = menuItems.find((item) => item.path === path);
  return item ? item.key : "dashboard";
});

// 主题切换相关
const isDarkMode = ref(false);

// 初始化主题
const initTheme = () => {
  const savedTheme = localStorage.getItem("theme");
  if (savedTheme === "dark") {
    isDarkMode.value = true;
    document.documentElement.classList.add("dark-mode");
  }
};

// 切换主题
const toggleTheme = (checked) => {
  isDarkMode.value = checked;
  if (checked) {
    document.documentElement.classList.add("dark-mode");
    localStorage.setItem("theme", "dark");
  } else {
    document.documentElement.classList.remove("dark-mode");
    localStorage.setItem("theme", "light");
  }
};

// 检查是否已登录
const isLoggedIn = ref(false);

// 初始化和监听登录状态
const updateLoginStatus = () => {
  isLoggedIn.value = checkLoginStatus();
};

// 处理菜单点击
const handleMenuClick = (e) => {
  const item = menuItems.find((item) => item.key === e.key);
  if (item) {
    router.push(item.path);
  }
};

// 切换菜单折叠状态
const toggleCollapsed = () => {
  collapsed.value = !collapsed.value;
};

// 页面加载时检查登录状态
onMounted(async () => {
  // 初始化主题
  initTheme();

  // 初始检查登录状态
  updateLoginStatus();

  // 根据登录状态进行重定向
  const token = localStorage.getItem("adminToken");
  if (!token && route.path !== "/") {
    router.push("/");
  } else if (token) {
    // 已登录，获取个人信息
    await fetchPersonalInfo();
  }

  // 监听个人信息更新事件
  eventBus.on("personalInfoUpdated", async () => {
    await fetchPersonalInfo();
  });

  // 监听路由变化，每次路由变化都重新检查登录状态
  const routeChangeHandler = () => {
    updateLoginStatus();
  };

  // 监听路由变化
  router.afterEach(routeChangeHandler);
});
</script>

<template>
  <Layout class="admin-layout" v-if="isLoggedIn">
    <Header class="admin-header">
      <div class="header-content">
        <div class="header-left">
          <div class="logo-container" :class="{ collapsed: collapsed }">
            <div class="logo-icon">
              <FileTextOutlined style="font-size: 24px; color: #fff" />
            </div>
            <div class="logo-text">Gulu Blog 管理系统</div>
          </div>
        </div>
        <div class="header-right">
          <div class="breadcrumb" v-if="!collapsed">
            {{
              menuItems.find((item) => item.key === currentMenuKey)?.label ||
              "首页"
            }}
          </div>
          <Switch
            :checked="isDarkMode"
            @change="toggleTheme"
            class="theme-toggle-switch"
            checked-children="🌞"
            un-checked-children="🌙"
            :title="isDarkMode ? '切换到明亮模式' : '切换到暗黑模式'"
          />
          <span v-if="!collapsed" class="theme-label">
            {{ isDarkMode ? "明亮模式" : "暗黑模式" }}
          </span>
          <Dropdown :trigger="['click']">
            <a class="user-info ant-dropdown-link" @click.prevent>
              <Avatar :src="currentUser.avatar" class="user-avatar" />
              <span class="user-name" v-if="!collapsed">{{
                currentUser.name
              }}</span>
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item
                  key="profile"
                  @click="
                    () => {
                      router.push('/personal-info');
                    }
                  "
                >
                  <UserOutlined />
                  个人信息
                </a-menu-item>
                <a-menu-item key="logout" @click="handleLogout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </Dropdown>
        </div>
      </div>
    </Header>
    <Layout class="main-layout">
      <Sider
        width="200"
        class="admin-sider"
        :collapsed="collapsed"
        :collapsible="true"
        :trigger="null"
        transition-name="sider-collapse"
      >
        <div class="sider-trigger" @click="toggleCollapsed">
          <MenuUnfoldOutlined v-if="collapsed" />
          <MenuFoldOutlined v-else />
        </div>
        <Menu
          mode="inline"
          :selectedKeys="[currentMenuKey]"
          @click="handleMenuClick"
          class="sider-menu"
          theme="light"
          :openKeys="[currentMenuKey]"
        >
          <Menu.Item v-for="item in menuItems" :key="item.key">
            <template #icon>
              <component :is="item.icon" />
            </template>
            {{ item.label }}
          </Menu.Item>
        </Menu>
      </Sider>
      <Content class="admin-content">
        <div class="content-wrapper">
          <RouterView />
        </div>
      </Content>
    </Layout>
  </Layout>
  <RouterView v-else />
</template>

<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
  overflow: hidden; /* 防止页面整体滚动 */
}

.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.admin-header {
  height: 64px;
  padding: 0 24px;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: fixed; /* 固定顶部 */
  top: 0;
  left: 0;
  right: 0;
}

.header-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo-container {
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.logo-container.collapsed .logo-text {
  display: none;
}

.logo-icon {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.logo-text {
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  white-space: nowrap;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.theme-toggle-switch {
  width: 60px;
  height: 24px;
}

.theme-toggle-switch + .ant-switch-handle {
  width: 20px;
  height: 20px;
  top: 2px;
}

.theme-label {
  color: #fff;
  font-size: 14px;
  margin-left: 8px;
}

/* 暗黑模式下的主题切换样式 */
:global(.dark-mode) .theme-label {
  color: #e0e0e0;
}

.breadcrumb {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  transition: opacity 0.3s ease;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-avatar {
  width: 36px;
  height: 36px;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.user-name {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
}

.main-layout {
  flex: 1;
  display: flex;
  background-color: #f0f2f5;
  padding-top: 64px; /* 为顶部栏留出空间 */
  height: 100vh;
  width: 100%;
}

.admin-sider {
  background-color: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.09);
  transition: all 0.3s ease;
  position: fixed; /* 固定侧边栏 */
  top: 64px; /* 在顶部栏下方 */
  bottom: 0;
  left: 0;
  z-index: 9;
  width: 200px;
}

/* 侧边栏折叠状态 */
.admin-sider.collapsed {
  width: 80px;
}

/* 侧边栏折叠过渡动画 */
.sider-collapse-enter,
.sider-collapse-leave-to {
  transform: translateX(-100%);
}

.sider-collapse-enter-to,
.sider-collapse-leave {
  transform: translateX(0);
}

.sider-collapse-enter-active,
.sider-collapse-leave-active {
  transition: transform 0.3s ease;
}

.sider-trigger {
  position: absolute;
  top: 10px;
  right: -12px;
  width: 24px;
  height: 24px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  z-index: 1;
  transition: all 0.3s ease;
}

.sider-trigger:hover {
  background-color: #f5f5f5;
  transform: scale(1.1);
}

.sider-menu {
  padding-top: 48px !important;
  height: 100%;
}

.sider-menu .ant-menu-item {
  height: 40px;
  line-height: 40px;
  padding: 0 20px !important;
  margin: 4px 0;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.sider-menu .ant-menu-item:hover {
  background-color: #f0f7ff;
  color: #1890ff;
}

.sider-menu .ant-menu-item-selected {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
}

.sider-menu .ant-menu-item-selected:hover {
  background-color: #bae7ff !important;
}

.admin-content {
  flex: 1;
  padding: 24px;
  margin-left: 200px; /* 侧边栏宽度，确保主内容不被遮挡 */
  overflow-y: auto; /* 主内容区域滚动 */
  transition: all 0.3s ease;
  height: calc(100vh - 64px); /* 顶部栏下方的高度 */
  width: calc(100% - 200px); /* 计算剩余宽度 */
}

/* 侧边栏折叠时，调整主内容区域的宽度和左边距 */
.main-layout:has(.admin-sider.ant-layout-sider-collapsed) .admin-content {
  margin-left: 80px;
  width: calc(100% - 80px);
}

/* 为了兼容性，保留原来的兄弟选择器方式 */
.admin-sider.ant-layout-sider-collapsed + .admin-content {
  margin-left: 80px;
  width: calc(100% - 80px);
}

/* 确保main-layout下的flex布局正确工作 */
.main-layout {
  position: relative;
  overflow: hidden;
}

/* 确保content-wrapper跟随admin-content宽度变化 */
.content-wrapper {
  width: 100%;
}

.content-wrapper {
  background-color: #fff;
  border-radius: 8px;
  min-height: 100%;
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-header {
    padding: 0 16px;
  }

  .header-right {
    gap: 16px;
  }

  .breadcrumb {
    display: none;
  }

  .user-name {
    display: none;
  }

  .admin-sider {
    z-index: 999;
  }

  .admin-content {
    padding: 16px;
    margin-left: 0;
    left: 0;
  }

  .admin-sider:not(.collapsed) ~ .admin-content {
    margin-left: 200px;
    left: 200px;
  }

  .content-wrapper {
    min-height: 100%;
  }
}

/* 加载动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.admin-content > * {
  animation: fadeIn 0.3s ease-out;
}
</style>
